/**
 * Created by onsen on 2017/4/5.
 * node.js 发包:直接引入此包，调用send_data方法即可。其它两个文件为对象的工厂类，防止全局的引用。
 */
var dgram = require('dgram');
var client = dgram.createSocket("udp4");
var buf_factory = require('./buf_factory');
var server = require('../config').server;


exports.send_data = function(secret_key, bid, uid, app_kind, bkey, step, content) {
    var buf = buf_factory.getBuf(secret_key, bid, uid, app_kind, bkey, step, content);
    if (pre_check(buf.length)) {
        sendMsg(buf);
        return true;
    } else { //数据太长打本地日志
        console.log('buf_length:' + buf.length);
        console.log('buf:' + buf);
        return false;
    }

}

function pre_check(length) {
    if (length < 1472) //udp数据包最大字节
        return true;
    return false;
}

function sendMsg(buf) {
    // console.log(server.port, server.ip);
    client.send(buf, 0, buf.length, server.port, server.ip, function(err) {
        if (err) {
            console.log('log_send_error:' + err);
        } else {
            // console.log('log_send_success');
        }

    });
}
